package com.example.plan.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.plan.common.BaseResponse;
import com.example.plan.common.PageRequest;
import com.example.plan.common.ResultUtils;
import com.example.plan.common.result.Result;
import com.example.plan.model.dto.user.UserQueryRequest;
import com.example.plan.model.dto.user.UserUpdateRequest;
import com.example.plan.model.entity.User;
import com.example.plan.exception.BusinessException;
import com.example.plan.exception.ErrorCode;
import com.example.plan.model.vo.UserVo;
import com.example.plan.service.UserService;
import com.example.plan.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.plan.utils.getEncryptPassword.getEncryptPassword;

/**
 * @author ASUS
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-03-01 19:07:17
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    @Override
    public Result<Long> userRegister(String userAccount, String userPassword, String checkPassword) {
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致");
        }
        //条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        String encryptPassword = getEncryptPassword(userPassword);
        User user = new User();
        user.setUser_account(userAccount);
        user.setPassword_hash(encryptPassword);
        user.setNickname("匿名用户");
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "注册失败,数据库错误");
        }
        return Result.success(user.getUser_id());

    }

    @Override
    public Result<User> userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        String encryptPassword = getEncryptPassword(userPassword);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("password_hash", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        if (user == null) {
            log.info("用户不存在或密码错误");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        request.getSession().setAttribute("user_login", user);
        user.setPassword_hash(null);
        return Result.success(user);
    }

    @Override
    public Result<String> logout(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user_login");
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "未登录");
        }
        request.getSession().removeAttribute("user_login");
        log.info("用户[{}]退出登录", user.getUser_id());
        return Result.success("退出成功");
    }

    @Override
    public User getUserInfo(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user_login");
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }
        return user;

    }

    @Override
    public Result<Page<UserVo>> getAllUsers(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user_login");
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录");
        }
        PageRequest pageRequest = new PageRequest();
        Page<User> userPage = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize());
        Page<User> page = this.page(userPage);
        Page<UserVo> page2 = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize(), page.getTotal());
        List<UserVo> userVOList = this.getUserVOList(userPage.getRecords());
        page2.setRecords(userVOList);
        Result<Page<UserVo>> pageResult = Result.success(page2);
        return pageResult;
    }

    @Override
    public Result<Page<UserVo>> getUsersByConditions(UserQueryRequest userQueryRequest) {
        PageRequest pageRequest = new PageRequest();
        Page<User> userPage = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize());
        Page<User> page = this.page(userPage, this.getUserQueryWrapper(userQueryRequest));
        Page<UserVo> page2 = new Page<>(pageRequest.getCurrent(), pageRequest.getPageSize(), page.getTotal());
        List<UserVo> userVOList = this.getUserVOList(userPage.getRecords());
        page2.setRecords(userVOList);
        return Result.success(page2);
    }


    @Override
    public UserVo getUserVO(User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        return userVo;
    }

    @Override
    public List<UserVo> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getUserQueryWrapper(UserQueryRequest userQueryRequest) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        Long userId = userQueryRequest.getUser_id();
        String phone = userQueryRequest.getPhone();
        int isDeleted = userQueryRequest.getIsDeleted();
        String userAccount = userQueryRequest.getUser_account();
        String nickname = userQueryRequest.getNickname();
        Date createdAt = userQueryRequest.getCreated_at();
        Date updatedAt = userQueryRequest.getUpdated_at();
        String username = userQueryRequest.getUsername();
        queryWrapper
                .eq(userId==null, "user_id", userId)
                .eq(StrUtil.isNotBlank(userAccount), "user_account", userAccount)
                .eq(StrUtil.isNotBlank(nickname), "nickname", nickname)
                .eq(StrUtil.isNotBlank(phone), "phone", phone)
                .eq(createdAt==null, "created_at", createdAt)
                .eq(updatedAt==null, "updated_at", updatedAt)
                .like(StrUtil.isNotBlank(username), "username", username);
        return queryWrapper;
    }

    @Override
    public Result<UserVo> updateUser(UserUpdateRequest userUpdateRequest) {
        Long userId = userUpdateRequest.getUser_id();
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean updateResult = this.updateById(user);
        if (!updateResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新用户信息失败，数据库错误");
        }
        UserVo userVo = this.getUserVO(user);
        return Result.success(userVo);
    }

    @Override
    public Result<Boolean> deleteUser(Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空或无效");
        }

        try {
            User user = this.getById(id);
            if (user == null) {
                log.warn("尝试删除不存在的用户: userId={}", id);
                return Result.failed(false);
            }

            if (user.getIsDeleted() == 1) {
                log.info("用户已被软删除: userId={}", id);
                return Result.failed(false);
            }

            boolean result = this.lambdaUpdate()
                    .set(User::getIsDeleted, 1)
                    .eq(User::getUser_id, id)
                    .update();

//            if (result) {
//                log.info("成功软删除用户: userId={}", id);
//            } else {
//                log.warn("软删除用户失败: userId={}", id);
//            }
            return Result.success(result);
        } catch (Exception e) {
            log.error("软删除用户失败: userId={}", id, e);
            return Result.failed(false);
        }
    }

    private String encryptPassword(String password) {
        if (StrUtil.isBlank(password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码不能为空");
        }
        return getEncryptPassword(password);
    }

    @Override
    public Result<Boolean> updateUserPassword(Long userId, String oldPassword, String newPassword) {
        if (userId == null || StrUtil.hasBlank(oldPassword, newPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (newPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码过短");
        }

        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        String encryptOldPassword = encryptPassword(oldPassword);
        if (!user.getPassword_hash().equals(encryptOldPassword)) {
            log.error("旧密码错误: userId={}", userId);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "旧密码错误");
        }

        user.setPassword_hash(encryptPassword(newPassword));
        boolean updateResult = this.updateById(user);
        if (!updateResult) {
            log.error("密码更新失败,数据库错误: userId={}", userId);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "密码更新失败，数据库错误");
        }

        log.info("密码更新成功: userId={}", userId);
        return Result.success(true);
    }

    @Override
    public Result<Boolean> resetUserPassword(Long userId, String newPassword) {
        if (userId == null || StrUtil.hasBlank(newPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (newPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码过短");
        }

        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        String encryptNewPassword = getEncryptPassword(newPassword);
        user.setPassword_hash(encryptNewPassword);
        boolean updateResult = this.updateById(user);
        if (!updateResult) {
            log.error("密码重置失败,数据库错误: userId={}", userId);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码重置失败,数据库错误");
        }

        log.info("密码重置成功: userId={}", userId);
        return Result.success(true);
    }


    @Override
    public BaseResponse<Boolean> recoverUser(Long userId) {
        if (userId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        User user = this.getOne(queryWrapper);

        if (user == null) {
            log.error("用户不存在: userId={}", userId);
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        if (user.getIsDeleted() == 0) {
            log.info("用户已经是激活状态: userId={}", userId);
            return ResultUtils.success(true);
        }

        user.setIsDeleted(0); // 修改为未删除状态
        boolean updateResult = this.updateById(user);
        if (!updateResult) {
            log.error("用户恢复失败,数据库错误: userId={}", userId);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "用户恢复失败，数据库错误");
        }

        log.info("用户恢复成功: userId={}", userId);
        return ResultUtils.success(true);
    }


    @Override
    public Result<List<UserVo>> exportUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = this.list(queryWrapper);
        return Result.success(this.getUserVOList(userList));
    }

    @Override
    public Result<Boolean> importUsers(List<User> users) {
        if (CollUtil.isEmpty(users)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }

        boolean saveBatchResult = this.saveBatch(users);
        if (!saveBatchResult) {
            log.error("用户数据导入失败");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户数据导入失败");
        }

        log.info("用户数据导入成功");
        return Result.success(true);
    }
}








